package com.jiaoyu.eduservice.controller.front;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiaoyu.commonutils.JwtUtils;
import com.jiaoyu.commonutils.R;
import com.jiaoyu.eduservice.client.CommentClient;
import com.jiaoyu.eduservice.entity.EduComment;
import com.jiaoyu.eduservice.service.EduCommentService;
import com.jiaoyu.servicebase.exceptionhandler.GuliException;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author lei
 * @since 2022-11-30
 */
@RestController
@RequestMapping("/eduservice/comment")
//@CrossOrigin
public class CommentFrontController {

    @Autowired
    private EduCommentService commentService;

    @Autowired
    private CommentClient commentClient;

    //根据课程id查询评论列表
    //分页查询评论
    //根据课程id查询评论列表
    @ApiOperation(value = "评论分页列表")
    @GetMapping("{page}/{limit}")
    public R index(
            @ApiParam(name = "page", value = "当前页码", required = true)
            @PathVariable long page,
            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable long limit,
            @ApiParam(name = "courseQuery", value = "查询对象", required = false)
            String courseId) {
        Page<EduComment> pageParam = new Page<>(page, limit);
        Map<String,Object> map=commentService.getCommentFrontList(pageParam,courseId);
        return R.ok().data(map);
    }

    //添加评论
    @PostMapping("addComment")
    public R addComment(@RequestBody EduComment comment, HttpServletRequest request) {
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberId)) {
            throw new GuliException(20001, "请先登录");
        }
        //如果不为空，证明已经登录过
        comment.setMemberId(memberId);
        //远程调用ucenter根据用户id获取用户信息
        Map map = commentClient.getUserId(memberId);

        Object object = map.get("userInfo");
        // 将list中的数据转成json字符串
        String jsonObject = JSON.toJSONString(object);
        //将json转成需要的对象
        EduComment userInfo = JSONObject.parseObject(jsonObject, EduComment.class);

        //设置名字和头像
        comment.setNickname(userInfo.getNickname());
        comment.setAvatar(userInfo.getAvatar());
        //保存评论
        commentService.save(comment);
        return R.ok();
    }
}

